using System;
using System.Collections;
using System.Configuration;
using System.Threading;
using System.Web;
using Concurso.Clases;
using ConcursoCV.UI.Clases;
using Curriculum.Modelo.Clases;
using Curriculum.Services;
using System.Web.Security;

namespace ConcursoCV.UI.Helper
{
	using System;
	using System.Collections.Specialized;
	using System.Configuration;
	using System.Security.Principal;
	using System.Xml;
	
	/// <summary>
	/// Summary description for SecurityHelper.
	/// </summary>
	public class SecurityHelper
	{			
		public SecurityHelper()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public static IPrincipal CurrentPrincipal 
		{
			get 
			{
				return System.Threading.Thread.CurrentPrincipal;
			}
		}

		public static string CurrentUserName
		{
			get
			{
				return Thread.CurrentPrincipal.Identity.Name;
			}
	
		}
		public static string GetUsuarioID( )
		{			
			UsuarioService svc = new UsuarioService();
			Usuario usr = svc.ObtenerUsuarioPorNombreYRol( CurrentUserName, RoleConverter.ToConfigurationName(GetRole()) );
			return usr.Rol.Id;
		}


		// Generic method for framework
		public static bool IsInRole(string roleGroup) 
		{
			IPrincipal principal = CurrentPrincipal;
			return principal.IsInRole( roleGroup );
		}

		public static bool EsAdminitrador() 
		{
			return IsInRole( RoleConverter.ToConfigurationName( Role.Administrador) );
		}

		public static bool EsDocente() 
		{
			return IsInRole( RoleConverter.ToConfigurationName( Role.Docente) );
		}

		public static bool EsJurado() 
		{
			return IsInRole( RoleConverter.ToConfigurationName( Role.Jurado) );
		}
		public static bool EsRoleGenerico() 
		{
			return IsInRole( RoleConverter.ToConfigurationName( Role.RolGenerico) );
		}

		public static IList GetRoles()
		{
			return ConfigurationSettings.GetConfig("roles") as IList;
		}

		private static void RedirectToUnauthorizedPage()
		{
			//#TODO: hacer la pagina de acceso denegado
			HttpContext.Current.Response.Redirect("Default.aspx?pid=210");						
		}
		public static Role GetRole()
		{
			// obtengo los roles permitidos del web.config
			IList roles = GetRoles();
			Role role = Role.NoAutorizado;
			foreach( object roleTemp in roles )
			{
				// pregunto si esta en el rol
				if ( IsInRole( roleTemp.ToString() ) )
				{
					role = RoleConverter.ToEnum( roleTemp.ToString() );
					break;
				}				
			}
			// si no esta en ningun rol lo redirecciono a la pantalla de
			// acceso denegado
			if( role == Role.NoAutorizado )
			{
				// redirecciono a la pantalla de acceso denegado
				RedirectToUnauthorizedPage();
			}		
			return role;
		}

	}
}
